import addIcon from '@/assets/images/AddIcon.png';
import bluetoothIcon from '@/assets/images/BluetoothIcon.png';
import scanIcon from '@/assets/images/scanIcon.png';
import CircleAddButton from '@/components/CircleAddButton';
import MenuBackdrop from '@/components/MenuBackdrop';
import PageContainer from '@/components/PageContainer';
import ProductConfig, { getConfigsSupportConfigNetwork, haveBleAddProduct } from '@/config/product';
import { isSuperApp, showCategory } from '@/config/template';
import { initCategory } from '@/config/utils';
import AppInfo from '@/container/AppInfo';
import { INorInjectProps, norInject } from '@/models';
import alarmPushModel from '@/models/alarmPush';
import deviceDetailModel from '@/models/deviceDetail';
import { DeviceList_Store_Key } from '@/models/deviceList';
import { DeviceShare_Store_Key } from '@/models/deviceShare';
import { getProductConfig } from '@/services/applicationConfig';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { parseDeviceShareId } from '@/utils/deviceShare';
import global from '@/utils/global';
import { checkIsLogin, getLoginInfo, goToLoginPage, haveLoginDataInit, setSentryUserInfo } from '@/utils/loginStatus';
import ScanQrcode from '@/utils/ScanQrcode';
import { Image, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import i18n from 'i18n-js';
import { observer } from 'mobx-react';
import { Component } from 'react';
import configWifiModel from '../configDevice/models/configWifi';
import SelectAppModalScreen from '../globalAlert/SelectAppModalScreen';
import DeviceList from './deviceList';
import NoneDevices from './noneDevices';
import ActionButton from '@/components/ActionButton';

interface IProps extends INorInjectProps {
  router: any;
}

const dstyle = GStyleSheet.create({
  text: {
    color: DynamicColors.normalTextColor,
    fontSize: '36rpx',
  },
  box: {
    width: '100rpx',
    height: '100rpx',
    backgroundColor: '#f4a',
  },
  titleView: {
    padding: 20,
    backgroundColor: DynamicColors.navBarColor,
    justifyContent: 'space-between',
  },
  scanIcon: {
    width: '52rpx',
    height: '52rpx',
  },
});

let initEnd = false;

@norInject(DeviceList_Store_Key, DeviceShare_Store_Key)
@observer
class Index extends Component<IProps> {
  initLoading = false;

  $instance = Taro.getCurrentInstance();

  state = {
    canConfigNetworkProducts: [],
    menuShow: false,
  };

  loopFetchDeviceListTimer: any;

  constructor(props: any) {
    super(props);
    Taro.showShareMenu({ withShareTicket: true });
  }

  componentWillMount() {
    // 自动初始化一次
    this.init(true);
    if (initEnd) {
      this.reInit();
    }
    if (showCategory()) {
      initCategory();
    }
  }

  componentDidMount() {
    this.checkoutUpdate();
    // setTimeout(() => {
    //   homes.addDevice({
    //     device: {
    //       mac: "virtual:102632:364294",
    //       productKey: '58747bfe6b38411db928504d363b0926'
    //     }
    //   })
    // }, 2000)
    // deviceDataModal.goToVirtualDeviceDetailPage(getItemForPk("3e673dd56cc4413e9086995b30ce3a06"));
  }

  parseRouterParams = () => {
    // 解析扫码或者分享点击进入该页面的路由参数
    const { deviceShare } = this.props;
    const { params } = this.$instance.router || {};
    let shareId = params?.shareId || null;
    if (!shareId && params?.q) {
      const url = decodeURIComponent(params.q);
      shareId = parseDeviceShareId(url);
    }
    if (!shareId) {
      return;
    }
    if (!global.token) {
      deviceShare?.updateShareId(shareId);
      goToLoginPage();
      return;
    }
    deviceShare?.acceptShare(shareId);
  };

  checkoutUpdate = () => {
    const updateManager = Taro.getUpdateManager();

    // updateManager.onCheckForUpdate(function (res) {
    //   // 请求完新版本信息的回调
    //   console.log(res.hasUpdate)
    // })
    updateManager.onUpdateReady(function () {
      Taro.showModal({
        title: i18n.t('UPDATE_TIP'),
        content: i18n.t('NEW_VERSION_IS_READY'),
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        },
      });
    });
    // updateManager.onUpdateFailed(function () {
    //   // 新版本下载失败
    // })
  };

  initProduct = async () => {
    if (isSuperApp()) {
      // 是超级app就读取超赛的配置
      const data = await getProductConfig();
      if (data.success && data.data && data.data.product_list && data.data.product_list.length > 0) {
        return ProductConfig.updateCacheProducts(data.data && data.data.product_list);
      } else {
        return ProductConfig.init();
      }
    } else {
      return ProductConfig.init();
    }
  };

  updateConfigProduct = () => {
    const list = getConfigsSupportConfigNetwork();
    this.setState({ canConfigNetworkProducts: list });
  };

  init = async (showLoading = true) => {
    if (this.initLoading || initEnd) return;
    this.initLoading = true;

    // 不管是不是登录，都可以初始化一次产品配置
    await this.initProduct();
    this.updateConfigProduct();

    // await userStateModel.loginSuccess({ uid: '077dd1dd6e5c496fa67d7dafba10a0d6', jwtAuthenticationDto: { token: '7308937c50d544fea2da458a5feffe73' } });

    const loginInfo = await getLoginInfo();
    if (loginInfo.token) {
      global.token = loginInfo.token;
      await haveLoginDataInit();
      setSentryUserInfo();
      alarmPushModel.getAlarmSetting();
      // console.log('init', res);
    } else {
      // 未登录，跳转到登录页面
      // goToLoginPage();
    }
    this.parseRouterParams();
    this.initLoading = false;
    initEnd = true;
  };

  // 点击分享的小程序进入后，产品列表为空
  reInit = () => {
    this.updateConfigProduct();
    this.parseRouterParams();
  };

  goConfigDevice = () => {
    if (checkIsLogin()) {
      this.setState({ menuShow: true });
    }
  };

  onShow = async () => {
    const { deviceList, deviceShare } = this.props;

    if (initEnd && checkIsLogin(false)) {
      deviceDetailModel.cleanData();
      await deviceList?.getDeviceList();
      await deviceShare?.init();
    }

    this.loopFetchDeviceListTimer && clearInterval(this.loopFetchDeviceListTimer)
    this.loopFetchDeviceListTimer = setInterval(() => {
      deviceList?.getDeviceList();
    }, 5000)
  };

  onHide = () => {
    this.loopFetchDeviceListTimer && clearInterval(this.loopFetchDeviceListTimer)
  }

  goToConifg = () => {
    const { canConfigNetworkProducts } = this.state;
    if (canConfigNetworkProducts.length == 1) {
      // 只有一个的时候，直接跳转配网
      configWifiModel.clearData();
      configWifiModel.goToConfig(canConfigNetworkProducts[0]);
    } else {
      Taro.navigateTo({ url: '/pages/configDevice/index' });
    }
  };

  goToBleAdd = () => {
    Taro.navigateTo({ url: '/pages/configDevice/bleAdd/index' });
  };

  closeMenu = () => {
    this.setState({ menuShow: false });
  };

  rendrMenu = ({ showBleAdd, showAddIcon }: { showBleAdd: boolean; showAddIcon: boolean }) => {
    const { menuShow } = this.state;
    const data = [];
    // if (showBleAdd) {
    //   data.push({ icon: bluetoothIcon, title: i18n.t('BLUETOOTH_ADD'), onClick: this.goToBleAdd });
    // }
    data.push({ icon: addIcon, title: i18n.t('ADD_DEVICE'), onClick: this.goToConifg });
    data.push({ icon: scanIcon, title: i18n.t('SCAN'), onClick: ScanQrcode });
    return (
      <MenuBackdrop data={data} visible={menuShow} onClose={this.closeMenu}>
        <CircleAddButton id='ADD_DEVICE_BUTTON' onClick={this.goConfigDevice} style={{ marginLeft: 36 }} />
      </MenuBackdrop>
    );
  };

  render() {
    const {
      deviceList: { data },
    } = this.props;
    const { canConfigNetworkProducts } = this.state;
    const haveDevices = data && data.length > 0;
    // console.log('haveDevices', haveDevices);
    const styles = dstyle.style;
    const showBleAdd = haveBleAddProduct();
    const showAddIcon = canConfigNetworkProducts && canConfigNetworkProducts.length > 0;

    return (
      <PageContainer title='' back={false} renderRight={<AppInfo />} onHide={this.onHide} onShow={this.onShow} isTab>
        <View style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          <View style={styles.titleView} className='centerFlex'>
            <Text>{i18n.t('MY_DEVICE')}</Text>
            <View style={{ display: 'flex', alignItems: 'center' }}>{this.rendrMenu({ showBleAdd, showAddIcon })}</View>
          </View>
          <View className='listFlex' style={{ display: 'flex', flexDirection: 'column' }}>
            {haveDevices ? (
              <DeviceList />
            ) : (
              <NoneDevices showAddIcon={showAddIcon} onPress={showAddIcon ? this.goConfigDevice : ScanQrcode} />
            )}
          </View>
          <ActionButton onPress={async () => {
            const info = await getLoginInfo();
            Taro.openEmbeddedMiniProgram({
              appId: 'wx37043daa20905688',
              path: 'pages/index/index?uid=' + info.uid + '&token=' + info.token,
              envVersion: 'release',
              extraData: {
                uid: info.uid,
                token: info.token,
              },
              success: (res) => {
                console.log('跳转成功', res);
              },
              fail: (err) => {
                console.log('跳转失败', err);
              }
            });
          }}>
            <Image style={{width: '100%',height: '100%'}} src='https://xbgroup-static.gizwits.com/cybertron/users/391941/media/home_icon_default@3x_1745820799223.png'></Image>
          </ActionButton>
        </View>
        <SelectAppModalScreen />
        
      </PageContainer>
    );
  }
}

export default Index;
